package com.cp.order.platform.web;

import com.cp.order.model.GoodsBrand;
import com.cp.order.model.GoodsType;
import com.cp.order.model.StoreHouse;
import com.cp.order.model.SysUser;
import com.cp.order.platform.BaseController;
import com.cp.order.utils.IWebUtils;
import com.cp.order.utils.ParseMD5;
import com.jfinal.aop.Clear;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;

public class HomeController extends BaseController {

	@Clear
	public void index() {
		if (IWebUtils.getCurrentSysUser(this) == null) {
			String contextPath = this.getRequest().getScheme() + "://" + this.getRequest().getServerName() + ":"
					+ this.getRequest().getServerPort() + this.getRequest().getContextPath();
			setAttr("ctx", contextPath);
			renderFreeMarker("login.html");
		} else {
			redirect("/home");
		}
	}
	
	public void home() {
		renderFreeMarker("home.html");
	}
	
	public void main() {
		setAttr("brand", JsonKit.toJson(GoodsBrand.dao.search()));
		setAttr("type", JsonKit.toJson(GoodsType.dao.search()));
		setAttr("store", JsonKit.toJson(StoreHouse.dao.search()));
		renderFreeMarker("main.html");
	}

	@Clear
	public void validateImg() {
		// 产生验证码
		renderCaptcha();
	}

	@Clear
	public void dologin() {
		String userCode = getPara("userCode");
		String userPwd = getPara("userPwd");
		SysUser user = SysUser.dao.getUserByCode(userCode);

		if (PropKit.getBoolean("devMode", true)) {
			if (user != null) {
				setSessionAttr("userSession", user);
				returnOK(user);
			} else {
				returnBusinessError("用户不存在");
			}
		} else {
			if (!validateCaptcha("vcode")) {
				returnBusinessError("验证码错误");
			} else if (user == null) {
				returnBusinessError("用户不存在");
			} else if (!ParseMD5.parseStrToMd5U32(userPwd).equals(user.getPwd())) {
				returnBusinessError("密码错误");
			} else {
				setSessionAttr("userSession", user);
				returnOK(user);
			}
		}

	}

	public void logout() {
		removeSessionAttr("userSession");
		redirect("/");
	}
}
